document.querySelector(".fanhui").onclick = function () {
    location.href = "./index.html"
}

let username = getCookie("username");

function getname(key) {
    // 转url地址
    let strData = location.href.split('?')[1];
    let arrData = strData.split('=')
    // console.log(arrData[1]);
    return decodeURI(arrData[1])
}


function getGoodlist() {
    // 假设getname函数已经正确实现了获取URL参数的功能
    const keyword = getname("name");
    // console.log(keyword);

    // 如果keyword存在，构建请求数据，否则直接返回
    ajaxUsePromise02({
        url: `http://localhost:3000/books`,
        method: "get",
        data: `keyword=${encodeURIComponent(keyword)}`
    }).then(res => {
        for (let i = 0; i < res.length; i++) {
            if (keyword == res[i].id) {
                getData(res[i])
            }
        }
    });
}

function click() {
    let tallbtn = document.querySelector("#tall-btn")
    let text = document.getElementById('text')
    // console.log(text);

    tallbtn.onclick = function () {
        let oIput = text.value
        comments(oIput)
    }
}

function getData(data) {
    console.log("跟地址栏相比对的书籍", data);
    saveCookie('id', data.id, 7)
    ajaxUsePromise02({
        url: `http://localhost:3000/comments`,
        method: "get",
    }).then(res => {
        res.forEach(element => {
            if (data.id == element.bookId) {
                console.log("跟书籍id比对下来相关的评论", element);
                console.log(data.id);
                console.log(element.bookId);
                saveCookie('bookId', element.bookId, 7)
            }
        });
    })

}


function comments(oIput) {
    if (oIput != "") {
        let username = getCookie('username')
        let bookId = getCookie('bookId')
        console.log(bookId);
        let time = gettime()
        ajaxUsePromise02({
            url: `http://localhost:3000/comments`,
            method: "post",
            data: `bookId=${bookId}&username=${username}&time=${time}&content=${oIput}`
        }).then(res => {

            location.href = `./list.html?category=${bookId}`
        })
    }

}


function gettime() {
    // 创建一个Date对象
    var now = new Date();

    // 获取年、月、日、小时、分钟和秒信息
    var year = now.getFullYear(); // 年
    var month = now.getMonth() + 1; // 月，JavaScript中月份是从0开始的，所以需要+1
    var day = now.getDate(); // 日
    var hour = now.getHours(); // 小时
    var minute = now.getMinutes(); // 分钟
    var second = now.getSeconds(); // 秒

    // 格式化日期和时间
    var formattedDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
    var formattedTime = hour + ':' + (minute < 10 ? '0' + minute : minute) + ':' + (second < 10 ? '0' + second : second);


    time = formattedDate + " " + formattedTime
    // console.log(time);
    return time

}

window.onload = function () {
    getGoodlist()
    click()
}
